import {Component, OnInit} from '@angular/core';
import * as io from 'socket.io-client';
import {environment} from '../../environments/environment';
import {BrowserUtils} from '../lunhui-web-front-utils/BrowserUtils';

@Component({
    selector: 'app-lunhui-web-front-message',
    templateUrl: './lunhui-web-front-message.component.html',
    styleUrls: ['./lunhui-web-front-message.component.scss']
})
export class LunhuiWebFrontMessageComponent implements OnInit {

    private socket: any;

    constructor() {
    }

    ngOnInit() {
        const result: boolean = BrowserUtils.checkToken();

        if (!result) {
            BrowserUtils.backToTarget('login');
            return;
        }

        this.socket = io.connect(environment.socketHost);

        this.receiveMessage(this.socket);
    }

    private receiveMessage(socket: any): void {
        const _this = this;

        socket.on('connected', (msg: any) => {
            console.log(msg);
            _this.sendMessage(socket, 'hello', {
                msg: 'hello i im client'
            });

        });
    }

    private sendMessage(socket: any, msgName: string, data: any): void {
        socket.emit(msgName, JSON.stringify(data));
    }

}
